package com.example.smartwaterapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.smartwaterapi.entity.Alarm;
import com.example.smartwaterapi.mapper.AlarmMapper;
import com.example.smartwaterapi.service.AlarmService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.time.LocalDate;

/**
 * 闹钟服务实现类
 */
@Slf4j
@Service
public class AlarmServiceImpl extends ServiceImpl<AlarmMapper, Alarm> implements AlarmService {

    @Override
    public List<Alarm> getAlarmsByUserId(Long userId) {
        LambdaQueryWrapper<Alarm> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Alarm::getUserId, userId)
               .eq(Alarm::getStatus, 1)
               .orderByAsc(Alarm::getHour)
               .orderByAsc(Alarm::getMinute);
        return this.list(wrapper);
    }

    @Override
    public List<Alarm> getAlarmsByUserIdAndDeviceId(Long userId, Long deviceId) {
        LambdaQueryWrapper<Alarm> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Alarm::getUserId, userId)
               .eq(Alarm::getDeviceId, deviceId)
               .eq(Alarm::getStatus, 1)
               .orderByAsc(Alarm::getHour)
               .orderByAsc(Alarm::getMinute);
        return this.list(wrapper);
    }

    @Override
    public boolean syncAlarm(Alarm alarm) {
        try {
            log.info("开始同步闹钟: userId={}, name={}, time={}:{}", 
                alarm.getUserId(), alarm.getName(), alarm.getHour(), alarm.getMinute());
            
            // 检查是否已存在相同时间和用户的闹钟
            LambdaQueryWrapper<Alarm> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Alarm::getUserId, alarm.getUserId())
                       .eq(Alarm::getDeviceId, alarm.getDeviceId())
                       .eq(Alarm::getHour, alarm.getHour())
                       .eq(Alarm::getMinute, alarm.getMinute())
                       .eq(Alarm::getStatus, 1);
            
            Alarm existingAlarm = this.getOne(queryWrapper);
            
            if (existingAlarm != null) {
                log.info("发现重复闹钟，更新现有闹钟: existingId={}, newData={}", 
                    existingAlarm.getId(), alarm);
                
                // 更新现有闹钟信息
                existingAlarm.setName(alarm.getName());
                existingAlarm.setRepeatMode(alarm.getRepeatMode());
                existingAlarm.setIsEnabled(alarm.getIsEnabled());
                existingAlarm.setBellType(alarm.getBellType());
                existingAlarm.setBellName(alarm.getBellName());
                existingAlarm.setUpdateTime(LocalDateTime.now());
                existingAlarm.setNextTriggerTime(LocalDateTime.of(
                    LocalDate.now(), 
                    LocalTime.of(alarm.getHour(), alarm.getMinute())
                ));
                
                return this.updateById(existingAlarm);
            }
            
            // 设置闹钟创建时间和下次触发时间
            LocalDateTime now = LocalDateTime.now();
            alarm.setCreateTime(now);
            alarm.setUpdateTime(now);
            alarm.setNextTriggerTime(LocalDateTime.of(
                LocalDate.now(), 
                LocalTime.of(alarm.getHour(), alarm.getMinute())
            ));
            
            // 保存新闹钟
            boolean result = this.save(alarm);
            if (result) {
                log.info("闹钟同步成功: userId={}, name={}, time={}:{}", 
                    alarm.getUserId(), alarm.getName(), alarm.getHour(), alarm.getMinute());
            } else {
                log.error("闹钟同步失败: userId={}, name={}", alarm.getUserId(), alarm.getName());
            }
            
            return result;
        } catch (Exception e) {
            log.error("同步闹钟异常: userId={}, name={}", alarm.getUserId(), alarm.getName(), e);
            return false;
        }
    }

    @Override
    public boolean syncAlarms(List<Alarm> alarms) {
        try {
            for (Alarm alarm : alarms) {
                if (!syncAlarm(alarm)) {
                    return false;
                }
            }
            log.info("批量闹钟同步成功，共{}个闹钟", alarms.size());
            return true;
        } catch (Exception e) {
            log.error("批量闹钟同步失败: {}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    public List<Alarm> getAlarmsToTrigger() {
        LocalDateTime now = LocalDateTime.now();
        LocalTime currentTime = now.toLocalTime();
        
        LambdaQueryWrapper<Alarm> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Alarm::getStatus, 1)
               .eq(Alarm::getIsEnabled, true)
               .and(w -> w.eq(Alarm::getHour, currentTime.getHour())
                         .eq(Alarm::getMinute, currentTime.getMinute()));
        
        return this.list(wrapper);
    }

    @Override
    public List<Alarm> getDisabledAlarmsByUserId(Long userId) {
        LambdaQueryWrapper<Alarm> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Alarm::getUserId, userId)
               .eq(Alarm::getStatus, 1)
               .eq(Alarm::getIsEnabled, false)
               .orderByDesc(Alarm::getUpdateTime);
        return this.list(wrapper);
    }

    @Override
    public boolean updateNextTriggerTime(Long alarmId, LocalDateTime nextTriggerTime) {
        try {
            Alarm alarm = new Alarm();
            alarm.setId(alarmId);
            alarm.setNextTriggerTime(nextTriggerTime);
            alarm.setUpdateTime(LocalDateTime.now());
            return this.updateById(alarm);
        } catch (Exception e) {
            log.error("更新闹钟下次触发时间失败: alarmId={}, error={}", alarmId, e.getMessage());
            return false;
        }
    }
    
    @Override
    public int cleanupOrphanAlarms() {
        try {
            log.info("开始清理孤儿闹钟...");
            
            // 删除设备不存在的闹钟
            LambdaQueryWrapper<Alarm> wrapper = new LambdaQueryWrapper<>();
            wrapper.notInSql(Alarm::getDeviceId, "SELECT id FROM device");
            
            List<Alarm> orphanAlarms = this.list(wrapper);
            if (orphanAlarms.isEmpty()) {
                log.info("没有发现孤儿闹钟");
                return 0;
            }
            
            int deletedCount = orphanAlarms.size();
            boolean success = this.removeBatchByIds(orphanAlarms.stream().map(Alarm::getId).toList());
            
            if (success) {
                log.info("成功清理{}个孤儿闹钟", deletedCount);
                return deletedCount;
            } else {
                log.warn("清理孤儿闹钟失败");
                return 0;
            }
            
        } catch (Exception e) {
            log.error("清理孤儿闹钟异常", e);
            return 0;
        }
    }
} 